import java.util.Arrays;

public class Solution1034 {
    int[] dx=new int[]{0,1,0,-1};
    int[] dy=new int[]{1,0,-1,0};
    int color;
    int[][] grid;

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        this.color = grid[row][col];
        int[][] map = new int[grid.length][grid[0].length];
        this.grid = new int[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            this.grid[i] = Arrays.copyOf(grid[i], grid[i].length);
        }
        color(grid, color, row, col, map);
        return grid;
    }
    
    public void color(int[][] grid,int color,int x,int y,int[][] map) {
        if (map[x][y] == 1) {
            return;
        }
        map[x][y] = 1;
        if (grid[x][y] != this.color) {
            return;
        }
        boolean b = false;
        for (int i = 0; i < 4; i++) {
            if (valid(grid, x + dx[i], y + dy[i])) {
                if (this.grid[x + dx[i]][y + dy[i]] != this.grid[x][y]) {
                    b = true;
                }
                color(grid, color, x + dx[i], y + dy[i], map);
            } else {
                b = true;
            }
        }
        if (b) {
            grid[x][y] = color;
        }
    }

    public boolean valid(int[][] grid,int x,int y) {
        return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length);
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(new Solution1034().colorBorder(new int[][]{{1,2,2,},{2,3,2}},0,1,3)));
    }
}


